package com.isoft.c2team3service2.config;

import com.isoft.c2team3service2.filter.JwtAuthenticationFilter;
import com.isoft.c2team3service2.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(authorize -> authorize
                        // 公开接口
                        .requestMatchers(
                                "/login/**",
                                "/login/repeat/**",
                                "/file/**",
                                "/email/**",
                                "/insert/**",
                                //首页
                                "/api/hot-news",
                                "/api/hot-posts",
                                "/api/star-avatars"
                        ).permitAll()

                        // 管理员专属接口
                        .requestMatchers(
                                "/admin/**",
                                "/artists/posts/{artistId}"
                        ).hasAuthority("ROLE_管理员")

                        // 艺人专属接口
                        .requestMatchers(
                                "/artist-private-posts/artist/received",
                                "/artists/posts/{artistId}"
                        ).hasAuthority("ROLE_艺人")

                        // 普通用户+艺人共享接口 - 修复关注/取消关注接口权限
                        .requestMatchers(
                                "/artist/**",
                                "/posts/**",
                                "/comments/**",
                                // 明确包含用户关注和取消关注的所有相关接口
                                "/user/follow/**",
                                "/artist/follow/**",
                                "/user/unfollow/**",
                                "/artist/unfollow/",
                                "/artist-private-posts/{artistId}",
                                "/artist-private-posts/user/all",
                                "/api/messages/**",
                                "/perf/**",
                                "/mounting/**",
                                "/private-post/**",
                                "/login/logout/**",
                                //关注接口
                                "/follow/users/**",
                                "/follow/artists/**",
                                "/follow/users/**",
                                "/follow/artist/**",
                                //查询他人页面
                                "/user/detail/**",
                                //查看访问时间
                                "/mounting/**",
                                //互相发消息
                                "/api/messages/**",
                                //上传背景图
                                "user/upload/**"
                        ).hasAnyAuthority("ROLE_普通用户", "ROLE_艺人")

                        // 剩余所有接口需登录
                        .anyRequest().authenticated()
                )
                .csrf(csrf -> csrf.disable())
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .userDetailsService(userDetailsService);

        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("http://localhost:5173");
        configuration.addAllowedMethod("*");
        configuration.addAllowedHeader("*");
        configuration.setAllowCredentials(true);
        // 允许跨域请求携带Authorization头
        configuration.addExposedHeader("Authorization");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
